package com.swordget.controller;

import com.alibaba.fastjson.JSONArray;
import com.swordget.commons.FileHandlerUtil;
import com.swordget.entity.TableDesign;
import com.swordget.entity.vo.*;
import com.swordget.exception.ResolveException;
import com.swordget.exception.VerifyFailException;
import com.swordget.service.HandlerLogService;
import com.swordget.service.ImportExportService;
import com.swordget.service.ImportDeleteService;
import com.swordget.service.facade.impl.ImportExportFacadeServcieImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.swordget.commons.SimpleFinalUtil.*;

/**
 * @Author: David
 * @Date: Created in 9:53 2020/4/15
 * @Description: 公共导入导出服务视图层接口
 * @Modified By:
 * @Version:
 */
@RestController
@RequestMapping("/importExport")
public class ImportExportController {

    private ImportExportService importExportServcie;

    private FileHandlerUtil fileHandleUtil;

    private HandlerLogService handlerLogService;

    private ImportDeleteService importDeleteService;
    @Autowired
    private ImportExportFacadeServcieImpl importExportFacadeServcie;

    @Autowired
    public ImportExportController(ImportExportService importExportServcie, FileHandlerUtil fileHandleUtil, HandlerLogService handlerLogService,ImportDeleteService importDeleteService,ImportExportFacadeServcieImpl importExportFacadeServcie) {
        this.importExportServcie = importExportServcie;
        this.fileHandleUtil = fileHandleUtil;
        this.handlerLogService = handlerLogService;
        this.importDeleteService = importDeleteService;
    }

    @PostMapping
    public SimpleResponseVo exportData(@RequestBody SimpleRequestVo<ExportVo> requestVo) {
        final String loginId = requestVo.getLoginId();
        final String handlerType = requestVo.getData().getHandlerType();
        final TableDesign tableDesign = requestVo.getData().getTable();
        final JSONArray queryParam = requestVo.getData().getQueryParams();
        final String [] serials = requestVo.getData().getSerials();
        final String dataStatus = requestVo.getData().getDataStatus();
        //判断要导出的类型，调用不同的接口进行导出
        String fileId = null;
        if (EXCEL.equals(handlerType)) {
            final ExcelVo excelVo = requestVo.getData().getExcel();
            fileId = importExportServcie.exportExcel(tableDesign, queryParam, serials, excelVo, loginId, dataStatus);
        } else if (CSV.equals(handlerType)) {
            final CsvOrTxtVo csvVo = requestVo.getData().getCsvOrTxtVo();
            fileId = importExportServcie.exportCsv(tableDesign, queryParam, serials, csvVo, loginId, dataStatus);
        } else if (TXT.equals(handlerType)) {
            final CsvOrTxtVo csvVo = requestVo.getData().getCsvOrTxtVo();
            final String fileId1 = importExportServcie.exportTxt(tableDesign, queryParam, serials, csvVo, loginId, dataStatus);
            fileId = fileId1;
        } else {
            throw new VerifyFailException("请检查您的请求参数!");
        }
        if (StringUtils.isBlank(fileId)) {
            return SimpleResponseVo.fail("导出失败!");
        }
        return SimpleResponseVo.success(fileId);
    }

    @GetMapping
    public void getFile(@RequestParam String fileId, HttpServletResponse response) {
        String filePath = handlerLogService.findUploadFilePath(fileId);
        SimpleResponseVo.responseFile(filePath, response);
    }


    @PostMapping("/resolve")
    public SimpleResponseVo resolveFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String type = multipartRequest.getParameter("type");
        String loginId = multipartRequest.getParameter("loginId");
        MultipartFile multipartFile = multipartRequest.getFile("uploadFile");
        if (null == multipartFile) {
            throw new ResolveException("没有解析到文件!");
        }
        //上传文件
        File file = fileHandleUtil.uploadFile(multipartFile, "UTF-8", loginId);
        if (null == file) {
            throw new ResolveException("文件上传失败!");
        }
        String fileNum = handlerLogService.addUploadLog(file, loginId);
        if (StringUtils.isBlank(fileNum)) {
            throw new ResolveException("无法获取上传文件序列号!");
        }
        ExportVo exportVo = null;
        if (EXCEL.equals(type)) {
            List<SheetVo> sheetVos = importExportServcie.resolveExcel(file, loginId);
            exportVo = ExportVo.builder()
                    .handlerType("excel")
                    .excel(ExcelVo.builder()
                            .sheets(sheetVos).build())
                    .fileId(fileNum)
                    .build();
        } else if (CSV.equals(type) || TXT.equals(type)) {
            exportVo = ExportVo.builder()
                    .handlerType(type)
                    .csvOrTxtVo(null)
                    .fileId(fileNum)
                    .build();
        } else {
            throw new VerifyFailException("请检查您的请求参数!");
        }
        //设置domain，用于跨域
        //System.out.println(multipartRequest.getContextPath());
        //String domain = "'localhost'";
        //String setDomain = "<script>document.domain = "+domain+";</script>";
        //String returnmsg = JSONObject.toJSONString(SimpleResponseVo.success(exportVo));
        //return (setDomain+returnmsg);
        return SimpleResponseVo.success(exportVo);
    }


    public SimpleResponseVo importFile(@RequestBody SimpleRequestVo<ImportVo> requestVo) {
        final ImportVo importVo = requestVo.getData();
        final String handlerType = importVo.getHandlerType();
        final TableDesign tableDesign = importVo.getTable();
        final String fileId = importVo.getFileId();
        final String loginId = requestVo.getLoginId();
        String orgId = "";
        boolean isImport = false;
        List<CsvOrTxtImportVo> result = importVo.getResult();
        importExportServcie.importFile(tableDesign, result, fileId, handlerType, loginId, orgId);
        return SimpleResponseVo.success();
    }

    /**
     * 解析文件头
     * @param resovleHeadVo
     * @return
     * @throws IOException
     */
    @PostMapping("/resolve/head")
    public SimpleResponseVo resolveHead(@RequestBody ResovleHeadVo resovleHeadVo) throws IOException {
        String handlerType = resovleHeadVo.getHandlerType();
        if (EXCEL.equals(handlerType)) {
            List<SheetVo> sheetVos = importExportServcie.resolveExcelHead(resovleHeadVo);
            ExcelVo excelVo = new ExcelVo(sheetVos);
            ExportVo exportV = ExportVo.builder()
                    .handlerType(handlerType)
                    .fileId(resovleHeadVo.getFileId())
                    .excel(excelVo)
                    .build();
            return SimpleResponseVo.success(exportV);
        } else if (CSV.equals(handlerType) || TXT.equals(handlerType)) {
            CsvOrTxtVo csvOrTxtVo = importExportServcie.resolveTxtHead(resovleHeadVo);
            ExportVo exportVo = ExportVo.builder()
                    .handlerType(handlerType)
                    .fileId(resovleHeadVo.getFileId())
                    .csvOrTxtVo(csvOrTxtVo)
                    .build();
            return SimpleResponseVo.success(exportVo);
        }
        throw new VerifyFailException("请检查您的请求参数!");
    }


    @PostMapping("/import")
    public SimpleResponseVo upload(MultipartHttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest =  request;
        //获取模板id
        String template = multipartRequest.getParameter("template");
        //获取templateImport
        String templateImport = multipartRequest.getParameter("templateImport");
        //获取tableId
        String tableId = multipartRequest.getParameter("tableId");
        //获取loginId
        String loginId = multipartRequest.getParameter("loginId");
        //获取orgId
        String orgId = multipartRequest.getParameter("orgId");
        //获取上传文件
        MultipartFile multipartFile = multipartRequest.getFile("uploadFile");
        if (multipartFile == null) {
            throw new ResolveException("没有检测到文件,请确认是否上传了文件!");
        }
        if (StringUtils.isBlank(template)) {
            throw new ResolveException("没有检测模板,请确认是否选择了模板!");
        }
        //上传文件
        File file = fileHandleUtil.uploadFile(multipartFile, "UTF-8", loginId);
        if (null == file) {
            throw new ResolveException("文件上传失败!");
        }
        String fileNum = handlerLogService.addUploadLog(file, loginId);
        if (StringUtils.isBlank(fileNum)) {
            throw new ResolveException("无法获取上传文件序列号!");
        }
        importExportFacadeServcie.resolveFile(template, tableId, fileNum, loginId, orgId,templateImport);
        return SimpleResponseVo.success();

    }

}
